<template>
  <div>
    <div class="clearfix">
      <a-button class="w-float-right" type="primary" size="small" :loading="loading" @click="saveBtnClick">
        保存
      </a-button>
      <span class="w-float-right">&nbsp;&nbsp;</span>
      <a-button
        v-if="$route.query.id"
        class="w-float-right"
        type="primary"
        size="small"
        @click="previewClick"
      >
        预览
      </a-button>
    </div>
    <br>
    <a-form :form="form" :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }">
      <a-form-item label="作品名称" prop="name">
        <a-input
          v-decorator="['name', { rules: [{ required: true, message: '请输入' }], initialValue: model ? model.name : '' }]"
          placeholder="请输入作品名称..."
        />
      </a-form-item>
      <a-form-item label="版本" prop="version">
        <a-input
          v-decorator="['version', { rules: [{ required: true, message: '请输入' }], initialValue: model ? model.version : '' }]"
          placeholder="请输入版本号..."
        />
      </a-form-item>
      <a-form-item label="地址">
        <a-input
          v-decorator="['url', { initialValue: model ? model.url : '' }]"
          placeholder="请输入地址..."
        />
      </a-form-item>
      <a-form-item label="个人介绍">
        <a-switch v-model="isShow" :default-checked="model ? model.isShow : false" />
      </a-form-item>
      <a-form-item label="封面" prop="cover">
        <w-up-image ref="WUpImage" :souce-url="cover" />
      </a-form-item>
      <a-form-item label="类型" prop="type">
        <a-input
          v-decorator="['type', { rules: [{ required: true, message: '请输入' }], initialValue: model ? model.type : '' }]"
        >
          <a-select slot="addonAfter" v-model="optionType" style="width: 80px" @change="typeChange">
            <a-select-option v-for="(v, k) in types" :key="k" :value="v">
              {{ v }}
            </a-select-option>
          </a-select>
        </a-input>
      </a-form-item>
      <a-form-item label="作品时间">
        <a-form-item :style="{ display: 'inline-block', width: '200px' }">
          <a-date-picker
            v-decorator="['startDate', { rules: [{ required: true, message: '请选择' }], initialValue: model ? model.startDate : null }]"
            style="width: 100%"
          />
        </a-form-item>
        <span :style="{ display: 'inline-block', width: '24px', textAlign: 'center' }">-</span>
        <a-form-item :style="{ display: 'inline-block', width: '200px' }">
          <a-date-picker
            v-decorator="['endDate', { rules: [{ required: true, message: '请选择' }], initialValue: model ? model.endDate : null }]"
            style="width: 100%"
          />
        </a-form-item>
      </a-form-item>
      <a-form-item label="描述">
        <a-input v-decorator="['describe', { initialValue: model ? model.describe : '' }]" type="textarea" placeholder="请输入描述..." />
      </a-form-item>
    </a-form>
    <w-editor ref="WEditer" @save="saveBtnClick" />
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { Api, Admin } from '@/config/api'
import WUpImage from '@/components/global/imageUp/oss'
import WEditor from '@/components/global/marked/index'
import { WrappedFormUtils } from 'ant-design-vue/types/form/form'
import Product from '@/models/product'

@Component({
  name: 'AdminWebProductAdd',
  layout: 'admin',
  components: {
    WUpImage,
    WEditor
  },
  async asyncData ({ app, route }) {
    const { $wAxios } = app
    const arr = [$wAxios.$get(Api.product.types)]
    if (route.query.id) {
      arr.push($wAxios.$get(`${Api.product.detail}${route.query.id}`))
    }
    const data = await Promise.all(arr)
    const [types, detail] = data
    const reData: any = {
      types,
      cover: ''
    }
    if (detail) {
      reData.model = detail
      reData.optionType = detail.type
      reData.cover = detail.cover
    }
    return reData
  },
  head () {
    return {
      title: '作品'
    }
  },
  data () {
    return {
      form: this.$form.createForm(this, { name: 'coordinated' })
    }
  }
})
export default class AdminWebProductAdd extends Vue {
  form!: WrappedFormUtils;
  cover = '';
  model: Product | null = null;
  isShow = false
  loading = false

  optionType = '';

  mounted () {
    if (this.model) {
      (this.$refs.WEditer as any).setData(this.model.content)
    }
  }

  typeChange (val: string) {
    this.form.setFieldsValue({
      type: val
    })
  }

  check () {
    return new Promise((resolve, reject) => {
      (this.$refs.WUpImage as any)
        .upImage()
        .then((data: any) => {
          this.cover = data
          this.form.validateFields((err, values) => {
            if (!err) {
              resolve(values)
            } else {
              this.$message.error('请完成填写')
              reject(err)
            }
          })
        })
        .catch(() => {
          this.$message.error('请选择封面图片')
        })
    })
  }

  previewClick () {
    window.open(`/web/product/${this.$route.query.id}`)
  }

  saveBtnClick () {
    this.loading = true
    this.check()
      .then((values: any) => {
        const p = {
          ...values,
          cover: this.cover,
          content: (this.$refs.WEditer as any).getData(),
          isShow: this.isShow
        }
        const url = this.$route.query.id
          ? `${Admin.product.update}${this.$route.query.id}`
          : Admin.product.create
        const method = this.$route.query.id ? '$put' : '$post'
        this.$wAxios[method](url, p)
          .then((data) => {
            this.$message.success('成功')
            if (!this.$route.query.id) {
              this.$router.replace({
                path: '/admin/web/product/add',
                query: { id: data._id }
              })
            }
          })
          .catch(() => {}).finally(() => {
            this.loading = false
          })
      })
      .catch(() => {
        this.loading = false
      })
  }
}
</script>

<style scoped></style>
